<script>
  import { Grid, Button, ActionIcon } from "@svelteuidev/core";
  import {
    Input,
    InputWrapper,
    Card,
    Title,
    Space,
    TypographyProvider,
    Accordion,
    Textarea,
    Modal,
    TextInput,
    Text,
  } from "@svelteuidev/core";
  import { Pencil2, Heart } from "radix-icons-svelte";
  import SvelteMarkdown from "svelte-markdown";
  import { onMount } from "svelte";
  let opened = false;
  let id = "";
  let topicDetail = {};
  let commentList = [];
  let commentid = -1;
  let agreeList = new Map();

  let newComment = {
    commiter: "",
    content: "",
    agree: 0,
    disagress: 0,
    time: new Date(),
    ischild: false,
    father: 0,
  };

  let newReply = {
    commiter: "",
    content: "",
    agree: 0,
    disagress: 0,
    time: new Date(),
    ischild: true,
    father: -1,
  };

  const addComment = () => {
    if (newComment.content) {
      let url = "/api/createcommit?id=" + id;
      fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(newComment),
      })
        .then((v) => v.json())
        .then((v) => {
          if (v.status !== 0) {
            console.log(v.status);
            console.log(v.msg);
            console.log("add failed");
            return;
          }
          console.log("add success");
          refreshPage();
        })
        .catch((e) => {
          if (!e.message) {
            console.log(e);
          } else {
            console.log(e.message);
          }
        });
    }
  };

  const addReply = () => {
    newReply.father = commentid;
    if (newReply.content && newReply.father !== -1) {
      let url = "/api/replycommit?id=" + id;
      fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(newReply),
      })
        .then((v) => v.json())
        .then((v) => {
          if (v.status !== 0) {
            console.log(v.status);
            console.log(v.msg);
            console.log("add failed");
            return;
          }
          console.log("add success");
          refreshPage();
        })
        .catch((e) => {
          if (!e.message) {
            console.log(e);
          } else {
            console.log(e.message);
          }
        });
    }
  };

  const handleAgree = () => {
    if (!commentList) return;
    commentList.forEach((item) => {
      if (!agreeList.has(item.id)) {
        agreeList.set(item.id, { change: false, type: null });
      }
      if (item.child) {
        item.child.forEach((child) => {
          if (!agreeList.has(child.id)) {
            agreeList.set(child.id, { change: false, type: null });
          }
        });
      }
    });
  };

  const changeAgree = (id, type) => {
    let currentStatus = agreeList.get(id);
    if (!currentStatus) {
      currentStatus = { change: false, type: null };
      agreeList.set(id, currentStatus);
    }

    if (currentStatus.change && currentStatus.type === type) {
      return;
    }

    commentList = commentList.map((item) => {
      if (item.id === id) {
        if (type) {
          item.agress++;
          if (currentStatus.change) item.disagress--;
        } else {
          item.disagress++;
          if (currentStatus.change) item.agress--;
        }
      } else if (item.child) {
        item.child = item.child.map((child) => {
          if (child.id === id) {
            if (type) {
              child.agress++;
              if (currentStatus.change) child.disagress--;
            } else {
              child.disagress++;
              if (currentStatus.change) child.agress--;
            }
          }
          return child;
        });
      }
      return item;
    });

    agreeList.set(id, { change: true, type: type });
  };

  const getid = (item) => {
    opened = true;
    commentid = item;
  };

  onMount(() => {
    const url = new URL(window.location.href);
    const params = new URLSearchParams(url.search);
    id = params.get("id");
    fetchdata();
    handleAgree();
  });

  async function fetchdata() {
    let url = "/api/detail?id=" + id;
    fetch(url, { method: "GET" })
      .then((v) => v.json())
      .then((v) => {
        if (v.status !== 0) {
          console.log(v.status);
          console.log(v.msg);
          console.log("read failed");
          return;
        }

        topicDetail = v.detail;
        commentList = v.detail.child || [];
        handleAgree();
      })
      .catch((e) => {
        if (!e.message) {
          console.log(e);
        } else {
          console.log(e.message);
        }
      });
  }

  function refreshPage() {
    location.reload();
  }
</script>

<div class="topic-detail">
  <Modal {opened} on:close={() => (opened = false)} title="请写下你的回复">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-right: 10px;">
      <div style="width: 80%;">
        <TextInput
          icon={Pencil2}
          placeholder="善言结善缘"
          radius="md"
          size="md"
          bind:value={newReply.content}
        />
      </div>
      <Button variant="light" color="pink" size="xs" on:click={addReply}>发送</Button>
    </div>
  </Modal>

  <Grid>
    <Grid.Col span={7}>
      <div class="topic-content">
        <Card>
          <Title order={1}>{topicDetail.title}</Title>
          <div style="display: flex;padding-top:10px; padding-bottom:10px; align-items:center">
            <div class="name">{topicDetail.owner}</div>
            <Space w={30} />
          </div>
          <div class="content">
            <TypographyProvider>
              <SvelteMarkdown source={topicDetail.content} />
            </TypographyProvider>
          </div>
        </Card>
      </div>
    </Grid.Col>
    <Grid.Col span={5}>
      <div style="display:flex;justify-content:space-between;align-items:center;margin-right: 10px;">
        <div style="width: 90%;">
          <TextInput
            icon={Pencil2}
            placeholder="善言结善缘"
            radius="md"
            size="md"
            bind:value={newComment.content}
          />
        </div>
        <Button variant="light" color="pink" size="xs" on:click={addComment}>发送</Button>
      </div>
      <div class="topic-comment">
        {#if commentList.length}
          {#each commentList as item (item.id)}
            <Accordion class="comment-items">
              <Accordion.Item value="typescript">
                <div slot="control">
                  <div style="display: flex;justify-content:space-between">
                    <div class="comment" style="display: flex;">
                      <div class="comment-provider">{item.commiter}：</div>
                      <div class="comment-content">{item.content}</div>
                    </div>
                    <div class="time">{item.time}</div>
                  </div>
                  <div style="display: flex;justify-content:space-between; padding-top:5px">
                    <div style="display: flex;align-items:center">
                      <Button variant="light" color="pink" size="xs" on:click={()=>changeAgree(item.id,true)}>👍</Button>
                      <Space w={10} />
                      <Text>{item.agress}</Text>
                      <Space w={10} />
                      <Button variant="light" color="pink" size="xs" on:click={()=>changeAgree(item.id,false)}>👎</Button>
                      <Space w={10} />
                      <Text>{item.disagress}</Text>
                    </div>
                    <Button
                      id = {item.id}
                      variant="light"
                      color="pink"
                      size="xs"
                      on:click={()=>getid(item.id)}>评论</Button>
                  </div>
                </div>
                {#if item.child && item.child.length}
                  {#each item.child as itam (itam.id)}
                    <div class="childcomment">
                      <div style="display: flex;justify-content:space-between">
                        <div class="comment" style="display: flex;">
                          <div class="comment-provider">{itam.commiter}:</div>
                          <div class="comment-content">{itam.content}</div>
                        </div>
                        <div class="time">{itam.time}</div>
                      </div>
                      <div style="display: flex;justify-content:space-between; padding-top:5px">
                        <div style="display: flex;align-items:center">
                          <Button variant="light" color="pink" size="xs" on:click={()=>changeAgree(itam.id,true)}>👍</Button>
                          <Space w={10} />
                          <Text>{itam.agress}</Text>
                          <Space w={10} />
                          <Button variant="light" color="pink" size="xs" on:click={()=>changeAgree(itam.id,false)}>👎</Button>
                          <Space w={10} />
                          <Text>{itam.disagress}</Text>
                        </div>
                      </div>
                    </div>
                  {/each}
                {/if}
              </Accordion.Item>
            </Accordion>
          {/each}
        {/if}
      </div>
    </Grid.Col>
  </Grid>
</div>



<style>
  .topic-detail {
    background-color: rgb(210, 207, 207);
    height: auto;
    margin-top: 10px;
  }
  .topic-content {
    padding-left: 10px;
    padding-right: 10px;
  }
  .topic-comment {
    margin-top: 10px;
    background-color: white;
    margin-right: 10px;
  }
  .time {
    font-size: small;
  }
  .childcomment {
    padding-top: 5px;
    margin-top: 10px;
    border-top: dashed rgb(200, 200, 200);
  }
</style>
